//
// Copyright (c) 2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.user;

import java.util.*;
import java.security.Principal;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.Globals;
import org.apache.commons.beanutils.PropertyUtils;

import com.broadvision.portal.services.util.TransferBeanUtils;
import com.broadvision.license2.*;
import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.web.servlet.SessionVisitor;
import com.broadvision.system.accesscontrol.client.*;
import com.broadvision.visitor.client.*;
import com.broadvision.visitor.exceptions.*;
import com.broadvision.portal.services.Channel;
import com.broadvision.portal.services.PortalVisitor;
import com.broadvision.visitor.client.VisitorManager;
import com.broadvision.visitor.interfaces.VisitorGroup;
import com.broadvision.visitor.client.VisitorGroupManager;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.web.action.Tab;
import com.broadvision.portal.services.OrganizationObjectInfo;

import com.broadvision.manage.common.tools.user.UserSearch;
import com.broadvision.manage.common.tools.user.UserProfile;
import com.broadvision.manage.tools.action.BaseAction;

/**
 * Saves a user's roles
 */
public class RoleSaveAction extends BaseAction {

  public static final VisitorManager visitorMgr = new VisitorManager();

  /**
   * Implements the action for saving a user's roles.
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                               throws Exception
  {
    try {
      PortalVisitor agent = getPortalVisitor(request);
      long serviceId = getServiceId(request);

      long userId = ((Long) UserUtils.getP(form, "userId")).longValue();

      UserProfile userProfile = new UserProfile(userId);
      userProfile.edit();
      TransferBeanUtils.copyPropertiesToModel(userProfile, form);
      
      userProfile.setCanEditRole(true);    

      String[] roles = null;    

      if (null != UserUtils.getP(form, "assignedRoles")) {
      roles = (String[]) UserUtils.getP(form, "assignedRoles");
      userProfile.setAssignedRoles(roles);
      }

      userProfile.setServiceId(serviceId);
      userProfile.updateRole(); 

      AccessManager accessMgr = AccessManager.instance();

      Visitor thisV = userProfile.getVisitor();
      PortalVisitor thisPV = new PortalVisitor(thisV, agent);

      // save channel admins
      boolean changeChannelIDs = ((Boolean) UserUtils.getP(form, "changeChannelIDs")).booleanValue();
      if (changeChannelIDs) {
      // revoke the existing roles

         try {
             List channelAdmins = accessMgr.getOwnerObjectsForPrincipal((Principal) thisV, UserProfile.CHANNEL_ADMIN);
             if (null != channelAdmins) {
                for (int j = 0; j < channelAdmins.size(); j++) {
                   ACObjectID ac = (ACObjectID) channelAdmins.get(j);
                   Channel ch = (Channel) Channel.getObject(ac, thisPV);
                   if (ch.getServiceId() == serviceId ) {
                      accessMgr.revokeRole(thisV, UserProfile.CHANNEL_ADMIN, ch);
                   }
                }
             }
         }
         catch (Exception ex) {
         }

         // grant the new ones
         if (null != UserUtils.getP(form, "channelIDs")) {
           Long[] newChIDs = (Long[]) UserUtils.getP(form, "channelIDs");
               for (int k = 0; k < newChIDs.length; k++) {
             try {
           Channel ch = new Channel((int)serviceId, newChIDs[k].longValue(), thisPV);
           accessMgr.grantRole(thisV, UserProfile.CHANNEL_ADMIN, ch);
             }
             catch (Exception ex) {
             }
           }
         }
      }

      // save org admins
      boolean changeGroupFQNs = ((Boolean) UserUtils.getP(form, "changeGroupFQNs")).booleanValue();
      if (changeGroupFQNs) {
      // revoke the existing roles
      try {
          List orgAdmins = accessMgr.getOwnerObjectsForPrincipal((Principal)thisV, UserProfile.ORGANIZATION_ADMIN);
          if (null != orgAdmins) {
             for (int j = 0; j < orgAdmins.size(); j++) {
                 ACObjectID ac = (ACObjectID) orgAdmins.get(j);
                 VisitorGroup vGroup = VisitorGroupManager.getVisitorGroupByFqn(ac.getObjectID().trim());
                 OrganizationObjectInfo org = new OrganizationObjectInfo(vGroup);
                 accessMgr.revokeRole(thisV, UserProfile.ORGANIZATION_ADMIN, org);
             }
          }
      }
      catch (Exception ex) {
      }

      // grant the new ones
      if (null != UserUtils.getP(form, "groupFQNs")) {
        String[] newOrgs = (String[]) UserUtils.getP(form, "groupFQNs");
            for (int k = 0; k < newOrgs.length; k++) {
                try {
                   VisitorGroup vGroup = VisitorGroupManager.getVisitorGroupByFqn(newOrgs[k]);
                   OrganizationObjectInfo org = new OrganizationObjectInfo(vGroup);
                   accessMgr.grantRole(thisV, UserProfile.ORGANIZATION_ADMIN, org);
                }
             catch (Exception ex) {
             }
           }
         }
      }
    }
    catch (Exception ex) {
       ex.printStackTrace();
       request.setAttribute(Globals.ERROR_KEY, "error.application");
       return mapping.findForward("failure");
    }
    return mapping.findForward("success");
  }
}
